import { reqGetUserInfo, reqLogin, reqLogout } from "@/api/user";
import { RootState } from "@/app/store";
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";

// 登陆的参数的数据类型
export interface LoginParams {
  username: string;
  password: string;
} 

// state的数据类型
interface UserState {
  token: string;
  name: string;
  avatar: string;
}

// 初始state
const initialState: UserState = {
  token: localStorage.getItem('user_token_key') || '',
  name: '',
  avatar: '',
}

// 登陆的异步action creator
export const loginAsync = createAsyncThunk(
  'user/loginAsync',
  ({username, password}: LoginParams) => reqLogin(username, password)
)

// 获取用户信息的异步action creator
export const getUserInfoAsync = createAsyncThunk(
  'user/getUserInfoAsync',
  () => reqGetUserInfo()
)

// 退出登陆的异步action creator
export const logoutAsync = createAsyncThunk(
  'user/logoutAsync',
  () => reqLogout()
)

// 当前redux模块的管理对象slice
const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {

  },
  extraReducers: (builder) => {
    builder
      // 登陆成功的reducer处理
      .addCase(loginAsync.fulfilled, (state, action) => {
        // 将token保存到state中
        state.token = action.payload.token
        // 将token保存到localStorage中
        localStorage.setItem('user_token_key', action.payload.token)
      })
      // 获取用户信息成功的reducer处理
      .addCase(getUserInfoAsync.fulfilled, (state, action) => {
        // 将用户信息保存到state中
        state.name = action.payload.name
        state.avatar = action.payload.avatar
      })
      // 登出成功的reducer处理
      .addCase(logoutAsync.fulfilled, (state) => {
        // 重置state中用户信息/token, 清除local中的token
        state.name = ''
        state.avatar = ''
        state.token = ''
        localStorage.removeItem('user_token_key')
      })
  }
})

// reducer函数
export const userReducer =  userSlice.reducer

// 读取模块状态数据的select函数
export const selectUser = (state: RootState) => state.user